package com.easygem.front.service.imp;

import com.easygem.common.model.front.CallLog;
import com.easygem.front.mapper.ConsumeLogMapper;
import com.easygem.front.service.ConsumeLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 廖思炜
 * @version 1.0
 * @className ConsumeLogServiceImpl
 * @Description TODO
 * @date 2025/3/25 9:14
 */
@Service
public class ConsumeLogServiceImpl implements ConsumeLogService {
    @Autowired
    private ConsumeLogMapper consumeLogMapper;
    /**
     * 根据当前为止往前7天时间查询
     *
     * @param map
     * @return
     */
    @Override
    public List<CallLog> getConsumeLogs(Map<String, Object> map) {
        List<CallLog> logs = new ArrayList<>();
        List<CallLog> result = new ArrayList<>();
        Map<Date, Double> dieJia = new HashMap<>();//该地方根据时间叠加每一个查询出来的消费金额


        if (map.get("startTime") == null && map.get("stopTime")!=null) {
            map.put("startTime", Timestamp.valueOf(LocalDateTime.now()));
        } else if (map.get("startTime") != null && map.get("stopTime") == null) {
            map.put("stopTime", Timestamp.valueOf(LocalDateTime.now()));
        } else if (map.get("startTime") == null && map.get("stopTime") == null) {
            map.put("startTime", Timestamp.valueOf(LocalDateTime.now().minusDays(7)));//当前时间-7天
            map.put("stopTime", Timestamp.valueOf(LocalDateTime.now()));
        }
        // 获取当前的截止时间
        Timestamp originalStopTime = Timestamp.valueOf((String)map.get("stopTime"));
        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalStopTime); // 将Calendar的时间设置为当前截止时间
        // 加一天
        calendar.add(Calendar.DATE, 1);
        // 设置新的截止时间
        map.put("stopTime",new Timestamp(calendar.getTimeInMillis()));

        logs= consumeLogMapper.getConsumeLogs(map);
        //将时分秒设置为0
        for (CallLog log : logs) {
            Date endTime = log.getEndTime(); // 假设log.getEndTime()返回的是java.util.Date类型
            calendar = Calendar.getInstance();
            calendar.setTime(endTime); // 设置当前时间

            // 清零时间部分（小时、分钟、秒、毫秒）
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Date truncatedTime = calendar.getTime(); // 获取处理后的日期
            log.setEndTime(truncatedTime); // 设置回log对象
            if (log.getDuration()==null){
                log.setConsumptionAmount(0.00);
            }else {
                log.setConsumptionAmount(log.getCircuitTariff()*log.getDuration());
            }
        }

        //将得到的相同一天的时间内的结果累加
        for (CallLog log : logs) {
            dieJia.merge(log.getEndTime(), log.getConsumptionAmount(), Double::sum);
        }
        //将结果存入CallLog作为消费日志返回
        for (Map.Entry<Date, Double> entry : dieJia.entrySet()) {
            CallLog log = new CallLog();
            log.setConsumptionAmount(entry.getValue());
            log.setEndTime(entry.getKey());
            result.add(log);
        }
        //不管结果顺序如何，对集合进行升序排序
        result.sort(Comparator.comparing(CallLog::getEndTime));
        return result;
    }

    /**
     * 默认根据七天范围内查询数据,当前账号下的所有数据
     *
     * @param map
     * @return
     */
    @Override
    public List<CallLog> getSeatsConsumeLog(Map<String, Object> map) {
        List<CallLog> logs = consumeLogMapper.getSeatsConsumeLog(map);
        for (CallLog log : logs) {
            // 获取当前的 endTime
            Date endTime = log.getEndTime();
            if (endTime != null) {
                // 使用 Calendar 修改时分秒毫秒部分
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endTime);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);

                // 直接修改 CallLog 中的 endTime 字段
                log.setEndTime(calendar.getTime());

                if (log.getDuration()==null){
                    log.setConsumptionAmount(0.00);
                }else {
                    log.setConsumptionAmount(log.getCircuitTariff()*log.getDuration());
                }
            }
        }
        List<CallLog> lastGuoLvLogs = new ArrayList<>();
        // 使用 HashMap 来存储已合并的日志，
        // key 为 user_id 和日期的组合（例如："user_id-date"）
        Map<String, CallLog> mergedLogs = new HashMap<>();

        for (CallLog log : logs) {
            Long userId = log.getUserId();
            Date getEndTime = log.getEndTime();

            String key = userId + "-" + getEndTime;
            if (mergedLogs.containsKey(key)) {
                // 合并消费金额
                CallLog existingLog = mergedLogs.get(key);
                existingLog.setConsumptionAmount(existingLog.getConsumptionAmount() + log.getConsumptionAmount());
            } else {
                // 新建一个 CallLog 对象并初始化
                CallLog newLog = new CallLog();
                newLog.setEndTime(log.getEndTime());
                newLog.setConsumptionAmount(log.getConsumptionAmount());
                newLog.setUserName(log.getUserName());
                newLog.setAccountName(log.getAccountName());
                mergedLogs.put(key, newLog);
            }
        }

        // 将合并后的日志添加到 lastGuoLvLogs 中
        lastGuoLvLogs.addAll(mergedLogs.values());
        //按照日期排序
        lastGuoLvLogs.sort(Comparator.comparing(CallLog::getEndTime));

        return lastGuoLvLogs;
    }

}
